package im

import (
	"dhfshop/models/isv"
	"dhfshop/controllers/base"
	"github.com/pkg/errors"
	wxpay "wxsdk/wxpay/wxapp"
	"wxsdk/wxpay/utils/pay"
	"github.com/astaxie/beego"
	"dhfshop/domain/im"
)

type PayNotifyController struct {
	base.BaseController
}

//微信异步回调
func (this *PayNotifyController) WeiXinPayNotify() {
	var (
		acPayParams *isv.AcPayParams
	)
	notifyData := this.Ctx.Input.RequestBody
	beego.Debug("WeiXinPayNotify notifyData:", string(notifyData))
    rspMap, err := wxpay.PayNotify(notifyData)
	if err != nil {
	    beego.Debug("PayNotify:", err.Error())
	    this.payReturnMessage("FAIL", err.Error())
		return
	}
	if rspMap["attach"] == "fuwuorder" {
	    acPayParams = new(isv.AcPayParams)
		acPayParams.MchTypeId = 1
		acPayParams.AppId = beego.AppConfig.String("SellerAppID")
		acPayParams.MchId = beego.AppConfig.String("SellerPayMchId")
		acPayParams.Appkey = beego.AppConfig.String("SellerPayAppKey")
	} else {
	    if rspMap["sub_appid"] != nil {
			acPayParams, err = isv.GetAcPayParamsBySubAppId(rspMap["sub_appid"].(string))  //特约商户返回
		}else {
			acPayParams, err = isv.GetAcPayParamsByAppId(rspMap["appid"].(string))
		}
	}
	if err != nil {
		err = errors.Wrap(err, "GetAcPayParamsByAppId... ")
		beego.Emergency(err.Error(),"WeiXinPayNotify notifyData:", string(notifyData))
		this.payReturnMessage("FAIL", err.Error())
		return
	}
	sign := payutils.MakeSign(rspMap, acPayParams.Appkey)
	if rspMap["sign"] != sign {
		beego.Emergency("notify sign is not equal", string(notifyData))
		this.payReturnMessage("FAIL", "notify sign is not equal")
		return
	}
	reqMap := make(map[string]string)
	for key, value := range rspMap {
	   reqMap[key] = value.(string)
	}
	reqMap["LocalKind"] = "PAY_NOTIFY"
	imlayer.PushMsgSvrIns.PushDao <- &reqMap
	//
	this.payReturnMessage("SUCCESS", "")  // 务必回复
	return
}

func (this *PayNotifyController) payReturnMessage(code, msg string) {
	asyNotifyRsp := map[string]interface{}{
		"return_code": code,
		"return_msg":  msg,
	}
	str := payutils.Map2Xml(asyNotifyRsp)
	this.Ctx.WriteString(str)
}


